package com.weilive.core.filter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.weilive.core.netty.NettyErrors;
import com.weilive.core.protocol.protobuf.ProtobufRequest;
import com.weilive.core.protocol.protobuf.ProtobufResponse;
import com.weilive.core.session.SessionAccount;
import com.weilive.core.session.SessionService;

/**
 * 登陆过滤
 * 
 * @author houzhiwei
 * 
 */
public class LoginFilter {
	// key:roleId value:当前时间
	private static final Map<Long, Map<String, Long>> RequestFrequency = new ConcurrentHashMap<Long, Map<String, Long>>();

	public static boolean doFilter(ProtobufRequest request) throws Exception {
		SessionAccount sAcct = request.getSessionAcct();

		if (sAcct != null && sAcct.isLogin()) {
			SessionAccount oldsAcct = SessionService.getSession(sAcct.getSessionId());
			if (oldsAcct == null && request.getType().equals("CSQ_Login")) {
				request.channel.write(ProtobufResponse.create(NettyErrors.USER_NOT_LOGIN, request.handler.getResponseType()));
				return false;
			}
			Map<String, Long> frequency = RequestFrequency.get(sAcct.getUserId());
			if (frequency == null) {
				frequency = new ConcurrentHashMap<String, Long>();
				RequestFrequency.put(sAcct.getUserId(), frequency);
			}
			Long nowTime = System.currentTimeMillis();
			Long upTime = frequency.get(request.getType());
			if (upTime == null) {
				upTime = 0L;
				frequency.put(request.getType(), upTime);
			}
			if (nowTime - upTime < request.handler.getRequestFrequency()) {
				return false;
			}
			frequency.put(request.getType(), nowTime);
			return true;
		}
		if (!request.getType().equals("CSQ_Login") && !request.getType().equals("CSQ_Connect")) {
			request.channel.write(ProtobufResponse.create(NettyErrors.USER_NOT_LOGIN, request.handler.getResponseType()));
			return false;
		}
		return true;
	}

	public static void removePlayerFilter(long playerId) {
		RequestFrequency.remove(playerId);
	}
}
